﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Data;

public partial class Pages_RoleManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitUI();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (btnSave.Text != "Save")
        {
            //UpdateRole();
        }
        else
        {
            AddRole();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearForm();
    }

    protected void grdRole_RowEditing(object sender, GridViewEditEventArgs e)
    {
        BindPageGrid();

        string strRoleName = ((Label)grdRole.Rows[e.NewEditIndex].FindControl("lblRoleName")).Text.Trim();

        //ObjectToForm(strRoleName);

        btnSave.Text = "Update";
    }

    protected void grdRole_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //if (new RoleManager().DeleteRole(((Label)grdRole.Rows[e.RowIndex].FindControl("lblRoleName")).Text.Trim()))
        //{
        //    ClearForm();
        //}
    }

    private void ClearForm()
    {
        txtRoleName.Text = string.Empty;
        txtDescription.Text = string.Empty;
        btnSave.Text = "Save";
        txtRoleName.Focus();
        lblMessege.Text = string.Empty;

        grdRole.SelectedRowStyle.Reset();

        BindPageGrid();
        BindRoleGrid();
    }

    private void InitUI()
    {
        BindRoleGrid();
        BindPageGrid();
    }

    private void BindRoleGrid()
    {
        IList<aspnet_Role> roleList = GetAllRoles();

        
        grdRole.DataSource = null;
        grdRole.DataSource = roleList;
        grdRole.DataBind();
    }

    private void BindPageGrid()
    {
        IList<XMLSiteMapParserObject> objXMLSiteMapParserObjectList = new List<XMLSiteMapParserObject>();

        objXMLSiteMapParserObjectList = ManageXMLController.ReadSiteMapNodes();
        grdPages.DataSource = objXMLSiteMapParserObjectList;
        grdPages.DataBind();
    }

    private void AddRole()
    {
        try
        {
            string roleName = txtRoleName.Text;
            IList<RolePagePermissionMap> rolePagePermissionMapList = GetRolePagePermissionMapList();
            if (rolePagePermissionMapList != null && rolePagePermissionMapList.Count > 0)
            {
                if (!Roles.RoleExists(roleName))
                {


                    Roles.CreateRole(roleName);
                    if (Roles.RoleExists(roleName))
                    {
                        SqlConnection sqlConnection = new SqlConnection(DBConnection.ConnectionString);
                        SqlCommand sqlCommand = new SqlCommand();
                        string SQL = "";
                        string query = string.Empty;
                        sqlCommand.CommandType = CommandType.Text;
                        sqlCommand.Connection = sqlConnection;
                        sqlCommand.CommandType = CommandType.Text;

                        SQL += "INSERT INTO RolePagePermissionMap (OID, RoleName, PageName) ";

                        query += SQL;
                        foreach (RolePagePermissionMap item in rolePagePermissionMapList)
                        {

                            query += " SELECT '" + item.OID + "' ,'" + roleName + "' ,'" + item.PageName + "' ";
                            query += " UNION ALL ";
                        }
                        int len = query.Length;
                        query = query.Substring(0,len - 11);

                        sqlCommand.CommandText = query;
                        try
                        {
                            sqlConnection.Open();
                            sqlCommand.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            sqlConnection.Close();
                        }
                        lblMessege.Text = "Role Create Successfully";
                    }
                    else
                    {
                        lblMessege.Text = "Role Cannot Create";
                    }
                }
                else
                {
                    lblMessege.Text = "Role Exist";
                }
            }
            else
            {
                lblMessege.Text = "No Page Permission ";
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private IList<aspnet_Role> GetAllRoles()
    {

        IList<aspnet_Role> roleList = new List<aspnet_Role>();

        SqlConnection sqlConnection = new SqlConnection(DBConnection.ConnectionString);
        SqlCommand sqlCommand = new SqlCommand();
        string sql;
        sql = string.Format("select * from aspnet_Roles");
        sqlCommand.CommandText = sql;
        sqlCommand.Connection = sqlConnection;
        sqlCommand.CommandType = CommandType.Text;
        try
        {
            sqlConnection.Open();
            
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            while (sqlDataReader.Read())
            {
                aspnet_Role role = new aspnet_Role();
                role.ApplicationId = new Guid(sqlDataReader["ApplicationId"].ToString());
                role.RoleId = new Guid(sqlDataReader["RoleId"].ToString());
                role.RoleName = sqlDataReader["RoleName"].ToString();
                role.LoweredRoleName = sqlDataReader["LoweredRoleName"].ToString();
                role.Description = sqlDataReader["Description"].ToString();
                roleList.Add(role);
            }

            sqlDataReader.Close();
        }
        catch(Exception ex)
        {
            return null;
        }
        finally{
            sqlConnection.Close();
        }
        return roleList;
    }

    public IList<RolePagePermissionMap> GetRolePagePermissionMapList()
    {
        IList<RolePagePermissionMap> rolePagePermissionMapList = new List<RolePagePermissionMap>();

        foreach (GridViewRow gVRow in grdPages.Rows)
        {
            if (((CheckBox)gVRow.FindControl("chkSelect")).Checked)
            {
                RolePagePermissionMap rolePagePermissionMapObj = new RolePagePermissionMap();
                rolePagePermissionMapObj.OID = Guid.NewGuid();
                rolePagePermissionMapObj.PageName = ((Label)gVRow.FindControl("lblTitle")).Text.Trim();

                rolePagePermissionMapList.Add(rolePagePermissionMapObj);
            }
        }

        return rolePagePermissionMapList;
    }
}
